//
//  UITextView+Extension.m
//  微博2期
//
//  Created by J on 15/12/17.
//
//

#import "UITextView+Extension.h"

@implementation UITextView (Extension)


- (NSMutableAttributedString*)insertAttrbuteText:(NSAttributedString*)text{
    
    
    return  [self insertAttrbuteText:text settingBlock:nil];
}


- (NSMutableAttributedString *)insertAttrbuteText:(NSAttributedString *)text settingBlock:(void (^)(NSMutableAttributedString *))settingBlock{
    
    
    
    NSMutableAttributedString * attributedText =[[NSMutableAttributedString alloc]init];
    [attributedText appendAttributedString:self.attributedText];//拼接之前文字
    
    NSUInteger loc = self.selectedRange.location;
//    [attributedText insertAttributedString:text atIndex:loc];//拼接文字
    [attributedText replaceCharactersInRange:self.selectedRange withAttributedString:text];//替换光标选中位置内容
    
    //        NSLog(@"%@",NSStringFromRange(self.textView.selectedRange));
    
    
    //插入属性文字到光标位置
    //            [attributedText addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, attributedText.length)];
    //
    //调用外面传进来的代码
    if (settingBlock) {
//        ^(NSMutableAttributedString *attributedText) {//在赋值之前调用Block
//            [attributedText addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, attributedText.length)];}(attributedText);
        
        settingBlock(attributedText);
//        
        };
    
    
    self.attributedText = attributedText;
    self.selectedRange = NSMakeRange(loc+1, 0);//之前选中的位置+1
    
    //        self.textView.font - > self.textView.text
    //        selectedRange : 控制textView文字选择范围 如果length ==0 selectedRange.location就是 TextView光标位置
    //        关于textView文字字体
    //        1.如果是普通文字 文字大小由textView.font控制
    //        2.如果是attributedText 文字大小由addAttribute设置字体
    
    return  attributedText;

    
    
    
}

@end
